package com.xm.controller;

import com.xm.common.annotation.RedisAnnotation;
import com.xm.common.pojo.JsonResult;
import com.xm.common.util.PageUtil;
import com.xm.pojo.Item;
import com.xm.service.ItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@CrossOrigin
@RequestMapping(value = "/item/")
@RestController()
public class ItemController {
    @Autowired
    ItemService itemService;


    @PostMapping
    JsonResult doSaveItem(@RequestBody Item item){
            itemService.saveItem(item);
            return new JsonResult("save ok");
    }

    @DeleteMapping("{id}")
    JsonResult doDeleteItem(@PathVariable Integer id){
        itemService.deleteItem(id);
        return new JsonResult("delete ok");
    }

    @PutMapping
    JsonResult doUpadteItem(@RequestBody Item item){
        itemService.updateItem(item);
        return new JsonResult("update ok");
    }

//    @RedisAnnotation(key ="itemFind")
    @GetMapping
    JsonResult doFindItem(Item item){
        return new JsonResult(PageUtil.startPage().doSelectPageInfo(()->
                itemService.findItem(item)));
    }

    @GetMapping("{id}")
    JsonResult doFindById(@PathVariable Integer id){
        return new JsonResult(itemService.findById(id));
    }

    @PutMapping("{id}/{number}")
    JsonResult doBuyItem(@PathVariable Integer id,
                         @PathVariable Integer number){
        int buyNum=number;
        int nowNum=itemService.findById(id).getNumber();

        if(buyNum>nowNum){
            return new JsonResult("商品数量不足,剩余"+nowNum+"件");
        }
        nowNum-=buyNum;
        Item item=new Item().setId(id).setNumber(nowNum);
        if(nowNum==0){
            item.setValid(0);
        }
        itemService.updateItem(item);
        return new JsonResult("购买成功");
    }
}
